'use strict';

const db = uniCloud.database();
const crypto = require('crypto');

exports.main = async (event, context) => {
  const { code, userInfo, mobile, smsCode } = event;
  
  // 参数校验
  if (!code) {
    return {
      code: 400,
      message: '微信授权码为必填项'
    };
  }
  
  try {
    // 这里应该调用微信API获取用户openid和session_key
    // 由于需要微信小程序配置，这里模拟返回
    // const wxApiUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
    
    // 模拟微信返回的数据
    const mockWxResponse = {
      openid: 'mock_openid_' + Date.now(),
      session_key: 'mock_session_key',
      unionid: 'mock_unionid_' + Date.now()
    };
    
    const { openid, unionid } = mockWxResponse;
    
    if (!openid) {
      return {
        code: 400,
        message: '微信授权失败，请重试'
      };
    }
    
    const userCollection = db.collection('uni-id-users');
    
    // 查找是否已有该微信用户
    let user = null;
    const existUserRes = await userCollection.where({
      wx_openid: openid
    }).get();
    
    if (existUserRes.data.length > 0) {
      user = existUserRes.data[0];
      
      // 检查用户状态
      if (user.status === 1) {
        return {
          code: 403,
          message: '账号已被禁用，请联系客服'
        };
      }
      
      // 更新最后登录信息
      const clientIP = context.CLIENTIP || '0.0.0.0';
      await userCollection.doc(user._id).update({
        last_login_date: new Date(),
        last_login_ip: clientIP
      });
      
      // 生成token
      const token = crypto.createHash('md5').update(user._id + Date.now() + 'tokenSalt').digest('hex');
      
      return {
        code: 200,
        message: '登录成功',
        data: {
          uid: user._id,
          mobile: user.mobile,
          nickname: user.nickname,
          avatar: user.avatar,
          token: token,
          isNewUser: false
        }
      };
    }
    
    // 新用户，需要绑定手机号
    if (!mobile || !smsCode) {
      return {
        code: 201,
        message: '需要绑定手机号',
        data: {
          openid: openid,
          needBind: true
        }
      };
    }
    
    // 验证手机号格式
    const mobileRegex = /^1[3-9]\d{9}$/;
    if (!mobileRegex.test(mobile)) {
      return {
        code: 400,
        message: '手机号格式错误'
      };
    }
    
    // 验证短信验证码
    const codeCollection = db.collection('sms-codes');
    const codeRes = await codeCollection.where({
      mobile: mobile,
      code: smsCode,
      type: 'register',
      used: false,
      expire_time: db.command.gt(new Date())
    }).get();
    
    if (codeRes.data.length === 0) {
      return {
        code: 400,
        message: '验证码无效或已过期'
      };
    }
    
    // 检查手机号是否已被其他用户绑定
    const mobileUserRes = await userCollection.where({
      mobile: mobile
    }).get();
    
    if (mobileUserRes.data.length > 0) {
      return {
        code: 400,
        message: '该手机号已被其他账号绑定'
      };
    }
    
    // 标记验证码已使用
    await codeCollection.doc(codeRes.data[0]._id).update({
      used: true
    });
    
    // 创建新用户
    const userData = {
      mobile: mobile,
      wx_openid: openid,
      wx_unionid: unionid,
      nickname: userInfo?.nickName || `微信用户${mobile.substr(-4)}`,
      avatar: userInfo?.avatarUrl || '',
      gender: userInfo?.gender || 0,
      status: 0,
      register_date: new Date(),
      agree_privacy: true
    };
    
    const createResult = await userCollection.add(userData);
    
    if (!createResult.id) {
      return {
        code: 500,
        message: '注册失败，请重试'
      };
    }
    
    // 生成token
    const token = crypto.createHash('md5').update(createResult.id + Date.now() + 'tokenSalt').digest('hex');
    
    return {
      code: 200,
      message: '注册并登录成功',
      data: {
        uid: createResult.id,
        mobile: mobile,
        nickname: userData.nickname,
        avatar: userData.avatar,
        token: token,
        isNewUser: true
      }
    };
    
  } catch (error) {
    console.error('微信登录错误：', error);
    return {
      code: 500,
      message: '服务器错误，请重试'
    };
  }
};